<template>
  <a-form layout="vertical" style="height: 60vh;width: 98%;">
    <a-form-item label="策略名称">
      <a-input v-model:value="formData.policyName" placeholder="请输入" />
    </a-form-item>

    <a-form-item label="超时条件">
      <a-radio-group v-model:value="formData.timeoutNode">
        <a-radio value="node">审批节点</a-radio>
          <a-radio value="task">审批任务</a-radio>
          <a-radio value="subFlow">子流程未结束</a-radio>
      </a-radio-group>
    </a-form-item>
    <a-form-item label="超时设置">
      <a-radio-group v-model:value="formData.timeoutConditions">
        <div class="timeout-condition">
          <a-radio value="duration">自然时长</a-radio>
          <a-radio value="workTime">工作时长</a-radio>
          <div class="sub-conditions">
            <label>停留时间:</label>
            <a-input-number v-model:value="formData.durationDays" :min="0" /> 天
            <a-input-number v-model:value="formData.durationHours" :min="0" /> 时
            <a-input-number v-model:value="formData.durationMinutes" :min="0" /> 分
          </div>
        </div>
      </a-radio-group>
    </a-form-item>

    <a-divider />

    <div v-for="(action, index) in executionActions" :key="index" class="action-block">
      <a-form-item label="执行动作">
        <a-select 
          v-model:value="action.type"
          placeholder="请选择执行动作"
          @change="handleActionChange(index)"
        >
          <a-select-option value="notifyPrivilege">通知特权人</a-select-option>
          <a-select-option value="notifyStarter">通知起草人</a-select-option>
          <a-select-option value="reminder">催办处理人</a-select-option>
          <a-select-option value="autoJump">自动跳过</a-select-option>
          <a-select-option value="autoTransfer">自动转办</a-select-option>
          <a-select-option value="returnToPreviousNode">退回上一个节点</a-select-option>
          <a-select-option value="returnToStartNode">退回起草节点</a-select-option>
          <a-select-option value="businessMethods">业务方法</a-select-option>
        </a-select>
      </a-form-item>

      <div v-if="action.type === 'notifyPrivilege'">
        <a-form-item label="通知方式">
          <a-select v-model:value="action.notifyMethod" mode="multiple" placeholder="请选择">
            <a-select-option value="sms">短信</a-select-option>
            <a-select-option value="email">邮件</a-select-option>
            <a-select-option value="app">应用内消息</a-select-option>
          </a-select>
        </a-form-item>

        <a-form-item label="消息内容">
          <a-radio-group v-model:value="action.messageOptions">
            <a-radio value="template">引用通知模板</a-radio>
            <a-radio value="custom">自定义消息内容</a-radio>
            <a-radio value="fullCustom">自定义标题和内容</a-radio>
          </a-radio-group>
        </a-form-item>

        <a-form-item label="消息模板" v-if="action.messageOptions.includes('template')">
          <a-select v-model:value="action.messageTemplate" placeholder="请选择">
            <a-select-option value="template1">模板1</a-select-option>
            <a-select-option value="template2">模板2</a-select-option>
          </a-select>
        </a-form-item>
      </div>

      <div v-if="action.type === 'autoTransfer'">
        <a-form-item label="转办对象">
          <a-select
            v-model:value="action.transferTarget"
            placeholder="请选择"
            :options="runTypeOptions"
          />
        </a-form-item>
        <a-form-item label="设置对象">
          <div style="border: 1px solid #e6e8eb;display: flex;justify-content: space-between;align-items: center;">
            <a-space>
              <div style="overflow: auto;" class="tagboxs">
                <a-tag closable @close="handleClose(tag,index)" v-for="tag in action.transferTargetData" :key="tag">
                  {{ tag.NAME }}
                </a-tag>
              </div>
            </a-space>
            <a-button style="margin-left: auto;" size="small" secondary type="info" @click="openMenuModal(index)">
              <template #icon>
                <a-icon><svg-icon name="touxiang" size="18" /></a-icon>
              </template>请选择
            </a-button>
          </div>
        </a-form-item>
      </div>
      <div v-if="action.type === 'businessMethods'">
        <a-form-item label="业务方法">
          <a-select
            v-model:value="action.methodList"
            placeholder="请选择"
            :options="methodList"
          />
        </a-form-item>
      </div>

      <a-button 
        type="link" 
        danger 
        @click="removeAction(index)"
        class="delete-btn"
      >
        删除
      </a-button>
      <a-divider />
    </div>

    <a-button type="dashed" @click="addAction" block>
      + 新增执行动作
    </a-button>

    <a-divider />
  </a-form>
</template>

<script setup lang="tsx">
import { reactive,ref,unref,computed } from 'vue';
import { message, Modal } from 'ant-design-vue';
import { useModal } from '@/hooks/useModal/useModal';
import {runTypeOptions}  from '@/components/design/components/DesignerCommCore/PanelOptions';
import SettingOrg from '@/components/setting/assigneeSetting.vue';
import { businessMethods } from '@/store/modules/businessMethod';

const formData = reactive({
  policyName: '',
  timeoutConditions: '',
  timeoutNode:'',
  durationDays: 0,
  durationHours: 0,
  durationMinutes: 0,
});
const [ModalRender, modalRef] = useModal()
const businessMethodStore = businessMethods();
const methodList = computed<[]>(() => businessMethodStore.bizMethods);
const editDrawerBindValue = reactive({
  defaultSelectData: [],
  runType:''
});

const executionActions = reactive([
  {
    type: '',
    notifyMethod: undefined,
    messageOptions: [],
    messageTemplate: undefined,
    transferTarget: undefined,
    transferTargetData:[],
    methodList:undefined
  }
]);

const addAction = () => {
  executionActions.push({
    type: '',
    notifyMethod: undefined,
    messageOptions: [],
    messageTemplate: undefined,
    transferTarget: undefined,
    transferTargetData:[],
    methodList:undefined
  });
};

const removeAction = (index) => {
  Modal.confirm({
    title: '确认删除',
    content: '确定要删除此执行动作吗？',
    okText: '确定',
    cancelText: '取消',
    centered: true, 
    onOk() {
      executionActions.splice(index, 1);
    }
  });
};

const handleActionChange = (index) => {
  executionActions[index].notifyMethod = undefined;
  executionActions[index].messageOptions = [];
  executionActions[index].messageTemplate = undefined;
  executionActions[index].transferTarget = undefined;
};

const editFormRef = ref<any>(null);
const openMenuModal = async(index)=>{
  if(executionActions[index].transferTarget==undefined||executionActions[index].transferTarget===""){
    message.warning("请选择转办对象");
    return false;
  }
  editDrawerBindValue.runType=executionActions[index].transferTarget;
  //editDrawerBindValue.defaultSelectData=taskInfo.value.TASK_RUN_DATA;
  ModalRender.show({
    title: '选择处理人',
    width: executionActions[index].transferTarget===0?'70%':'60%',
    // 是否显示右上角确定取消
    defaultExtra: true,
    destroyOnClose: true,
    content: () => {
      return <SettingOrg  ref={editFormRef} defaultData={unref(editDrawerBindValue)}></SettingOrg>;
    },
    // 确定方法执行
    onOk: async (values) => {
      const res = await editFormRef.value?.handleSubmit();
      console.log(res);
      if (!res) return;
      executionActions[index].transferTargetData =res;
      console.log(executionActions[index].transferTargetData);
    },
  });
};

//删除组织结构标签
const handleClose=(record,index)=>{
  executionActions[index].transferTargetData=executionActions[index].transferTargetData.filter((item)=>item.NO!==record.NO);
}

const handleSubmit = () => {
  console.log('提交数据：', {
    ...formData,
    executionActions: [...executionActions]
  });
  return {
    ...formData,
    executionActions: [...executionActions]
  };
};
//上级父页面调用
defineExpose({
  handleSubmit: handleSubmit,
});
</script>

<style scoped>
.timeout-condition {
  margin-bottom: 12px;
}

.sub-conditions {
  margin: 8px 0 0 24px;
}

.sub-conditions .ant-input-number {
  width: 80px;
  margin-right: 8px;
}

.action-block {
  position: relative;
  margin-bottom: 24px;
}

.delete-btn {
  position: absolute;
  right: 0;
  top: 0;
}
</style>